package com.xlserver.interceptor;

import com.xlserver.dao.LoginInfoMapper;
import com.xlserver.service.UserService;
import com.xlserver.util.TokenUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) throws Exception {
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        if (token != null){
            String userId = TokenUtil.getUserIdByToken(request);
            String password = userService.getPassword(userId);
            boolean result = TokenUtil.verify(token,userId,password);
            System.out.println("result: "+result);
            if(result){
                System.out.println("通过拦截器");
                return true;
            }
        }
        return false;
    }
}
